<?php
class LoginController extends Controller{
     public function indexAction(){
             if(strstr($_SERVER['SERVER_NAME'],'jiku999.com')){
                 $this->assign('is_select_api_key','none');
             }
             $this -> display('index');
     }

    /**
     * 验证码页面
     */
     public function vdcodeAction(){
         $image_lib = $this -> instance('pincode');
         $image_lib -> setSessionName('vis_tools_vdcode') -> show();
     }

    /**
     * 注销（登出）
     */
     public function logoutAction(){
         cookie :: set('vis_login_status', false);
         cookie :: set('vis_user_name', '');
         cookie :: set('vis_user_id', '');
         cookie :: set('vis_api_key', '');
         cookie :: set("app_id",0);
         // 跳转至登陆页面
        $this -> redirect($this -> _createUrl('login/index'));
     }
    
    /**
     * 分析是否登陆
     */
    protected function validate_login(){       
        $login_state = cookie :: get('vis_login_status');
        if ($login_state == true){
            // 跳转向首页
            $this -> redirect($this -> _createUrl('index/index'));
        }else{
			$this -> redirect($this -> _createUrl('login/index'));
		}
        
        return true;
    }
	
	public function loginAction(){
        $user_name = $this -> post('vis_account');
        $password = $this -> post('vis_password');
        $api_key = $this -> post('api_key');
        $user_info = LoginHelper::login(array("account"=>$user_name,"password"=>md5($password)),$api_key);
        $user_info['s_name']=$user_name;
        $user_info['s_id']=1000;
        if( count($user_info) > 0 ){
            // cookie设置的周期为8小时
            cookie::set("vis_api_key",$api_key.".grain");
            cookie :: set('vis_login_status', true, 28800);
            cookie :: set('vis_user_name', $user_info['s_name']?$user_info['s_name']:$user_info['s_tel'], 28800);
            cookie :: set('vis_user_id', $user_info['s_id']?$user_info['s_id']:$user_info['s_id'], 28800);
            //TODO 记录登录日志
            Model::instance('Model')->setConfig($this->getConfig('db_sys'))->setTableName('t_sys_log_admin_login')
                ->insert(array('user_name'=>$user_name,'user_id'=>$user_info['user_id'],'login_ip'=>http::getIp()));
            $this -> redirect($this -> _createUrl('index/index'));
        } else {
            $this -> showMessage('用户不存在或者信息有误，请联系管理员', $this -> _createUrl('login/index'), 3);
        }
	}
}
